package cn.com.xf.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import cn.com.xf.common.Constants;
import cn.com.xf.common.HttpUtils;

public class PasswordTools {

	public static  String sort(String enPass, String token, String timestamp, String nonce) {
		String[] strArray = { enPass, token, timestamp, nonce };
		Arrays.sort(strArray);
		StringBuilder sb = new StringBuilder();
		for (String str : strArray) {
			sb.append(str);
		}

		return sb.toString();
	}
	
	public static String sha1(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();

			StringBuffer hexString = new StringBuffer();

			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String getEncodedPassword(String password) {
		String nonce = UUID.randomUUID().toString();
		String timestamp = System.currentTimeMillis()+"";
		
		String sortString = sort(password, Constants.TOKEN, timestamp, nonce);
		String signature = sha1(sortString);

		
		String url = "http://218.16.125.165:30003/xfplatform-encrypt-0.0.1-SNAPSHOT/?reqType=getPwd&signature="+signature+"&timestamp="+timestamp+"&nonce="+nonce+"&enPass="+password;
		String url2 = "http://218.16.125.165:8009/xfplatform-encrypt-0.0.1-SNAPSHOT/?reqType=getPwd&signature="+signature+"&timestamp="+timestamp+"&nonce="+nonce+"&enPass="+password;
		String result = HttpUtils.getHtmlByUrl(url,"utf-8");
		if (result.equals("")) {
			result = HttpUtils.getHtmlByUrl(url2,"utf-8");
		}
		JSONParser js = new JSONParser();
		try {
			JSONObject json = (JSONObject) js.parse(result);
			String encoded = json.get("msg")+"";
			return encoded;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
}
